package org.example;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.io.File;
import java.io.FileOutputStream;

public class IMFileReceiver {
    public static void main(String[] args) throws Exception {
        // 创建消费者，并指定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("file_translate_group");
        // 指定NameServer地址
        consumer.setNamesrvAddr("124.71.28.51:9876");
        // 订阅主题
        consumer.subscribe("FileTransferTopic", "*");
        // 注册消息监听器
        consumer.registerMessageListener((MessageListenerConcurrently) (msgs, context) -> {
            for (MessageExt msg : msgs) {
                // 假设每个消息都是一个完整的文件
                try {
                    // 文件输出路径，这里假设使用消息ID作为文件名
                    String outputPath = "D:\\Desktop\\test\\" + msg.getKeys();
                    System.out.println(outputPath);
                    File file = new File(outputPath);
                    try (FileOutputStream fos = new FileOutputStream(file)) {
                        // 写入文件内容
                        fos.write(msg.getBody());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            }
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        });

        // 启动消费者
        System.out.println("Consumer Start");
        consumer.start();
    }
}